<?php
/*
Plugin Name: Tebe
Plugin URI: http://25labs.com
Description: A brief description of my plugin
Version: 0.1
Author: Tebe Tensing
Author URI: http://25labs.com
License: GPLv2
*/

/*  Copyright 2011  Tebe Tensing  (email : tebetensing@gmail.com)
        
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
        
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
        
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/


register_activation_hook( __FILE__, 'tt_tebe_install' );

function tt_tebe_install() {
	
	//register the uninstall function
    register_uninstall_hook( __FILE__, 'tt_tebe_uninstaller' );

	if ( $tt_tebe_options = get_option( 'tt_tebe_options' ) == FALSE ) {
		$tt_tebe_options = array(
			'facebook-enable' =>  0,
			'facebook-app-id' =>  '',
			'facebook-app-secret' =>  '',
			'google-enable' => 0,
			'google-client-id' => '',
			'google-client-secret' => ''
		);
		update_option( 'tt_tebe_options', $tt_tebe_options );
	}
  
    //do cool activation stuff
}

function tt_tebe_uninstaller() {
        
    //delete any options, tables, etc the plugin created
    delete_option( 'tt_tebe_options' );
        
}

register_deactivation_hook( __FILE__, 'tt_tebe_uninstall' );
        
function tt_tebe_uninstall() {
    //do something when plugin deactivated
//    delete_option( 'tt_tebe_options' );
}

add_action( 'admin_menu', 'tt_tebe_create_menu' );
             
function tt_tebe_create_menu() {
             
//create a submenu under Settings
    add_options_page( 'Tebe Settings Page', 'Tebe Settings',
        'manage_options', __FILE__, 'tt_tebe_settings_page' );
}

function tt_tebe_settings_page() {
	$tt_tebe_options = get_option('tt_tebe_options');
	if(isset($_POST['save-facebook'])) {
		if(isset($_POST['enable-facebook'])) $tt_tebe_options['facebook-enable'] = 1;
		else $tt_tebe_options['facebook-enable'] = 0;
		$tt_tebe_options['facebook-app-id'] = $_POST['appid'];
		$tt_tebe_options['facebook-app-secret'] = $_POST['appsecret'];
		update_option( 'tt_tebe_options', $tt_tebe_options );
		
	}
	else if(isset($_POST['save-google'])) {
		if(isset($_POST['enable-google'])) $tt_tebe_options['google-enable'] = 1;
		else $tt_tebe_options['google-enable'] = 0;	
		$tt_tebe_options['google-client-id'] = $_POST['clientid'];
		$tt_tebe_options['google-client-secret'] = $_POST['clientsecret'];
		update_option( 'tt_tebe_options', $tt_tebe_options );
		
	}

	    ?> 
     <div class="wrap"> 
     	<?php screen_icon( 'plugins' ); ?>
        <h2> My Plugin </h2>
        <h3>Facebook Settings</h3>
        <form method="POST" action="" > 
         <table class="form-table" > 
         <tr valign="top" > 
             <th scope="row" ><label for="featured" >Enable Facebook login</label></th> 
             <td><input type="checkbox" name="enable-facebook" <?php if($tt_tebe_options['facebook-enable'] == 1 ) echo 'checked=\"yes\"'; ?> /></td> 
         </tr>
         <tr valign="top" > 
             <th scope="row" ><label for="appid" >App ID</label></th> 
             <td><input maxlength="100" size="50" name="appid" value="<?php echo($tt_tebe_options['facebook-app-id']); ?>" /></td> 
         </tr> 
         <tr valign="top" > 
             <th scope="row" ><label for="appsecret" >App Secret</label ></th> 
             <td><input maxlength="100" size="50" name="appsecret" value="<?php echo($tt_tebe_options['facebook-app-secret']); ?>" /></td> 
         </tr> 
         <tr valign="top" > 
             <td> 
             <input type="submit" name="save-facebook" value="Save Options" class="button-primary" /> 
             </td> 
         </tr> 
         </table> 
         </br>
         <h3>Google Settings</h3>
         <table class="form-table" > 
         <tr valign="top" > 
             <th scope="row" ><label for="featured" >Enable Google login</label></th> 
             <td><input type="checkbox" name="enable-google" <?php if($tt_tebe_options['google-enable'] == 1 ) echo 'checked=\"yes\"'; ?> /></td> 
         </tr>
         <tr valign="top" > 
             <th scope="row" ><label for="appid" >Client ID</label></th> 
             <td><input maxlength="100" size="50" name="clientid" value="<?php echo($tt_tebe_options['google-client-id']); ?>" /></td> 
         </tr> 
         <tr valign="top" > 
             <th scope="row" ><label for="appsecret" >Client Secret</label ></th> 
             <td><input maxlength="100" size="50" name="clientsecret" value="<?php echo($tt_tebe_options['google-client-secret']); ?>" /></td> 
         </tr> 
         <tr valign="top" > 
             <td> 
             <input type="submit" name="save-google" value="Save Options" class="button-primary" /> 
             </td> 
         </tr> 
         </table>
         </form>
     </div>
     <?php
}

add_action('login_init','tt_tebe_login_init');

function tt_tebe_login_init() {
	

	
	require_once(dirname (__FILE__) . '/facebook/facebook.php');
	
	global $tt_tebe_fb_login_url;
	global $tt_tebe_google_login_url;
	global $tt_tebe_user_profile;
	global $tt_tebe_refresh_token;
	global $tt_tebe_access_token;
	global $wpdb;
	
	$tt_tebe_options = get_option('tt_tebe_options');

	// Create our application instance
	$tt_tebe_facebook = new Facebook(array(
		'appId'		=> $tt_tebe_options['facebook-app-id'],
		'secret'	=> $tt_tebe_options['facebook-app-secret']
		));
		
	// Get login URL
	$tt_tebe_fb_login_url = $tt_tebe_facebook->getLoginUrl(array(
		'scope'			=> 'email',
		'redirect_uri'	=> 'http://25labs.com/wp-login.php'
		));
	
	// change to dynamic url	
	$tt_tebe_google_login_url = 'https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=google_profile&redirect_uri=http%3A%2F%2F25labs.com%2Fwp-login.php&response_type=code&client_id=' . $tt_tebe_options['google-client-id'] . '&access_type=offline';
	
	
	
	
	
	
	
	
//$tt_tebe_fb_user = $facebook->getUser();

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	if($_GET['state'] == 'google_profile' ) {
		$tt_tebe_auth_code = $_GET['code']; //google auth redirect
		
		$fields=array(
    		'code'=>  urlencode($tt_tebe_auth_code),
    		'client_id'=>  urlencode($tt_tebe_options['google-client-id']),
    		'client_secret'=>  urlencode($tt_tebe_options['google-client-secret']),
   			'redirect_uri'=>  urlencode('http://25labs.com/wp-login.php'),
   			'grant_type'=>  urlencode('authorization_code')
		);

		$post = '';
		foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
		$post = rtrim($post,'&');

		$curl = curl_init();
		curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
		curl_setopt($curl,CURLOPT_POST,TRUE);
		curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
		$result = curl_exec($curl);
		curl_close($curl);

		$response =  json_decode($result,TRUE);
		$accesstoken = $response['access_token'];
		
		if(isset($response['refresh_token'])) $tt_tebe_refresh_token = $response['refresh_token'];
		else $tt_tebe_refresh_token = NULL;

		$tt_tebe_goo_user = "@@@@@";
	}
	elseif ($_GET['state']) $tt_tebe_fb_user = $tt_tebe_facebook->getUser(); //facebook auth redirect
	
	
	
	
/* *************************************************8	
	
	

// if session set
//		$tt_tebe_fb_user = from session
// 		get access token from database and $tt_tebe_facebook->setAccessToken('AAADUW7EAVJYBZCNdrZCTqTEEgmrImK9AVpHQxwZD');
// else
		list($temp,$temp2) = explode('.', $tt_tebe_options['google-client-id'], 2);

		if ( isset( $_COOKIE['tt_tebe_'. $tt_tebe_options['facebook-app-id']] ) ) {
			list($tt_tebe_user_from_cookie, $tt_tebe_access_token_hash) = explode('.', $_COOKIE['tt_tebe_'. $tt_tebe_options['facebook-app-id']], 2);
			$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_login = %s", $tt_tebe_user_from_cookie) );
			$tt_tebe_access_token = get_user_meta($user_id, 'access_token', true);
			if ( strcmp ( hash_hmac('sha256', $tt_tebe_access_token, $tt_tebe_options['facebook-app-secret'], false), $tt_tebe_access_token_hash ) == 0 ) {

				$tt_tebe_facebook->setAccessToken($tt_tebe_access_token);

				$tt_tebe_fb_user = $tt_tebe_user_from_cookie;
//				echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
			}
			else {
				setcookie('tt_tebe_' . $tt_tebe_options['facebook-app-id'], $tt_tebe_user_from_cookie . '.' . $tt_tebe_access_token_hash, time()-60*60*24*365, "/");
				
//				echo "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
				
				try {
					$tt_tebe_user_profile = $tt_tebe_facebook->api('/me');
					$tt_tebe_fb_user = $tt_tebe_facebook->getUser();
				}catch(FacebookApiException $e){
					wp_redirect( site_url('/wp-login.php') );
					exit;
				}
							
			}
		}
		elseif ( isset( $_COOKIE['tt_tebe_'. $temp] ) ) {//google cokkie set make access token from refresh token

				list($tt_tebe_user_from_cookie, $tt_tebe_refresh_token_hash) = explode('.', $_COOKIE['tt_tebe_'. $temp], 2);
				$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_login = %s", $tt_tebe_user_from_cookie) );
				$tt_tebe_refresh_token = get_user_meta($user_id, 'refresh_token', true);
				if ( strcmp ( hash_hmac('sha256', $tt_tebe_refresh_token, $tt_tebe_options['google-client-secret'], false), $tt_tebe_refresh_token_hash ) == 0 ) {
//			echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
					$refresh_fields=array(
							'refresh_token'=>  urlencode($tt_tebe_refresh_token),
    						'client_id'=>  urlencode($tt_tebe_options['google-client-id']),
    						'client_secret'=>  urlencode($tt_tebe_options['google-client-secret']),
							'grant_type'=>  urlencode('refresh_token')
						);

					$post = '';
					foreach($refresh_fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
					$post = rtrim($post,'&');

					$curl = curl_init();
					curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
					curl_setopt($curl,CURLOPT_POST,TRUE);
					curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
					curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
					curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
					$result = curl_exec($curl);
					curl_close($curl);

					$response =  json_decode($result,TRUE);
					$accesstoken = $response['access_token'];

//					$tt_tebe_goo_user = $tt_tebe_user_from_cookie;
					$tt_tebe_goo_user = "@@@@@";
//					echo "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
				}
				else {
					list($temp,$temp2) = explode('.', $tt_tebe_options['google-client-id'], 2);
					setcookie('tt_tebe_' . $temp, 0, time()-60*60*24*365, "/");
					wp_logout();
				}
		}
//		else {
//				$tt_tebe_fb_user = $tt_tebe_facebook->getUser();
//			echo "zzzzzzzzzzzzzz" . $tt_tebe_fb_user . "zzzzzzzzzzzzzzzzz";
//		}
********************************************** */
	
	if ( $tt_tebe_fb_user ) {
//		echo "if tt tebe start";
			try{

				// Proceed knowing you have a logged in user who's authenticated.
				$tt_tebe_user_profile = $tt_tebe_facebook->api('/' . $tt_tebe_fb_user );
				$tt_tebe_user_profile['provider'] = "facebook";

				$tt_tebe_access_token = $tt_tebe_facebook->getAccessToken();

			

				$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_email = %s", $tt_tebe_user_profile['email']) );
				
				if ( $user_id ) {
					update_user_meta($user_id, 'access_token', $tt_tebe_access_token);
				}
			
//set session session[addpi] = $tt_tebe_access_token.hash_hmac(----,tt_tebe_access_token, app_secret,false);
//store access token indatabase
			}catch(FacebookApiException $e){
//				error_log($e);
// unset session

				
//				$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_login = %s", $tt_tebe_fb_user ) );

//				$tt_tebe_user_temp = $tt_tebe_fb_user ;
				$tt_tebe_fb_user = NULL;
				$tt_tebe_user_profile = NULL;
//				echo "nullnullnullnullnullnull";
			}
//			echo " if tt tebe user";
	}
	
	elseif ($tt_tebe_goo_user == "@@@@@") {
		$url = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$accesstoken;

		$curl = curl_init();
		curl_setopt($curl,CURLOPT_URL,$url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
		$xmlresponse = curl_exec($curl);
		curl_close($curl);
		
		

		$tt_tebe_user_profile = json_decode($xmlresponse, TRUE);
		$tt_tebe_user_profile['provider'] = "google";
		if(isset($tt_tebe_user_profile['email'])) {			
			$tt_tebe_goo_user = $tt_tebe_user_profile['id'];
			list($temp,$temp2) = explode('.', $tt_tebe_options['google-client-id'], 2);
//			setcookie('tt_tebe_' . $temp, $tt_tebe_goo_user . '.' . hash_hmac('sha256', $tt_tebe_refresh_token, $tt_tebe_options['google-client-secret'], false), time()+60*60*24*365, "/");
//			setcookie('tt_tebe_' . $tt_tebe_options['facebook-app-id'], 0, time()-60*60*24*365, "/");
			
			//**********************************when register refreshtoken generated and user not registered. so cant enter into database
			$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_email = %s", $tt_tebe_user_profile['email']) );
			if ( $user_id && $tt_tebe_refresh_token ) {
				update_user_meta($user_id, 'refresh_token', $tt_tebe_refresh_token);				
				$tt_tebe_refresh_token = NULL;
			}
			//***************************************************************88
		}
		else {
			$tt_tebe_user_profile = NULL;
			$tt_tebe_goo_user = NULL;
			list($temp,$temp2) = explode('.', $tt_tebe_options['google-client-id'], 2);
//			setcookie('tt_tebe_' . $temp, 0, time()-60*60*24*365, "/");
		}
	}
	
	else {
		$tt_tebe_user_profile = NULL;
	}
	
$_POST['rememberme'] = 'rememberme'; //remember me always	
}

add_action('login_form','tt_tebe_add_login_button');
add_action('register_form','tt_tebe_add_login_button');




function sc_render_comment_form_social_connect() {
	if( comments_open() && !is_user_logged_in()) {
		tt_tebe_add_login_button();
	}
}
//add_action( 'comment_form_top', 'sc_render_comment_form_social_connect' );












function tt_tebe_add_login_button() {
	global $action;
	global $tt_tebe_fb_login_url;
	global $tt_tebe_google_login_url;
	if ($action == 'register') $temp = 'Register'; else $temp = 'Login';
	echo '<p id="connect-with" ><label>' . $temp . ' with</label></p><p id="social-icons" >
		<a onclick="displayConnectbox(' . $tt_tebe_fb_login_url . ');return false;" href="' . $tt_tebe_fb_login_url . '" ><img class="fac" src="' . plugins_url( 'images/a.png' , __FILE__ ). '" width="1px" height="1px" /></a>
		<a href="' . $tt_tebe_google_login_url .'" ><img class="goo" src="' . plugins_url( 'images/a.png' , __FILE__ ). '" width="1px" height="1px" /></a>
		<!--<a href="#" ><img class="twi" src="' . plugins_url( 'images/a.png' , __FILE__ ). '" width="1px" height="1px" /></a>-->
		<!--<a href="#" ><img class="wor" src="' . plugins_url( 'images/a.png' , __FILE__ ). '" width="1px" height="1px" /></a>-->
		<!--<a href="#" ><img class="yah" src="' . plugins_url( 'images/a.png' , __FILE__ ). '" width="1px" height="1px" /></a>-->
		</p>';
		
		if ($action == 'login' || $action == 'register') echo '<a onclick="displayNormalbox();return false;" id="normal-login-text" href="#" >Don\'t have a Facebook or Google account?</a>
		<a onclick="displayConnectbox();return false;" id="connect-login-text" href="#" >Use your Facebook or Google account?</a>
		';	
}


function set_cookie() {
//	$_POST['rememberme'] = 'rememberme';
	if(isset($_GET['redirect_to'])) {
		setcookie ( 'redirect_to', $_GET['redirect_to']);
	}
}
add_action( 'init', 'set_cookie',1);



add_action ('login_head', 'tt_tebe_login');
//add_action ('wp_head', 'tt_tebe_login');

function tt_tebe_wp_head() {
	require_once(dirname (__FILE__) . '/facebook/facebook.php');
	
	global $tt_tebe_fb_login_url;
	global $tt_tebe_google_login_url;
	
	$tt_tebe_options = get_option('tt_tebe_options');

	// Create our application instance
	$tt_tebe_facebook = new Facebook(array(
		'appId'		=> $tt_tebe_options['facebook-app-id'],
		'secret'	=> $tt_tebe_options['facebook-app-secret']
		));
		
	// Get login URL
	$tt_tebe_fb_login_url = $tt_tebe_facebook->getLoginUrl(array(
		'scope'			=> 'email',
		'redirect_uri'	=> 'http://25labs.com/wp-login.php'
		));
	
	// change to dynamic url	
	$tt_tebe_google_login_url = 'https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=google_profile&redirect_uri=http%3A%2F%2F25labs.com%2Fwp-login.php&response_type=code&client_id=' . $tt_tebe_options['google-client-id'] . '&access_type=offline';
	
	tt_tebe_login();
}

function tt_tebe_login() {
	global $action;



	$tt_tebe_image_url = plugins_url( 'images/provider_sprite_35_35.png' , __FILE__ );
	if ($action == 'login' || $action == 'register' || 1) {
		echo '<style type="text/css">';
		
		if($action == 'register') {
			echo 'form p{display:none;}	#connect-with,#social-icons {	display:block;text-decoration:none;}	 #login {text-align:center;}';
		}
		elseif($action == 'login') {
			echo 'form p{display:none;}	#connect-with,#social-icons {	display:block;text-decoration:none;} ';
		}

if ($action == 'login' || $action == 'register') echo '#connect-with, #social-icons {text-align:center;	}
h1 a {  background-image:url('.get_bloginfo('template_directory').'/images/25-labs-login-logo.png)  !important; } 


#normal-login-text{
	display:block;
	margin-bottom: 10px;
	text-align:center;
}
#connect-login-text{
	display:none;
	margin-bottom: 10px;
	text-align:center;
}';
echo 'img.fac
{
width:37px;
height:37px;
background:url("'.$tt_tebe_image_url.'") 0 0;
}
img.goo
{
width:37px;
height:37px;
background:url("'.$tt_tebe_image_url.'") -38px 0;
}
img.twi
{
width:37px;
height:37px;
background:url("'.$tt_tebe_image_url.'") -75px 0;
}
img.wor
{
width:37px;
height:37px;
background:url("'.$tt_tebe_image_url.'") -112px 0;
}
img.yah
{
width:37px;
height:37px;
background:url("'.$tt_tebe_image_url.'") -149px 0;
}';

if ($action == 'login' || $action == 'register') echo '</style>
<script type="text/javascript">
function displayNormalbox()
{
if(document.getElementById("loginform")) var el = document.loginform.getElementsByTagName("p");
else var el = document.registerform.getElementsByTagName("p");
for(var i=0;i<el.length;i++){ 
el[i].style["display"] = "block"; 
} 
document.getElementById("normal-login-text").style["display"] = "none";
document.getElementById("connect-login-text").style["display"] = "block";
document.getElementById("connect-with").style["display"] = "none";
document.getElementById("social-icons").style["display"] = "none";
}
function displayConnectbox()
{
if(document.getElementById("loginform")) var el = document.loginform.getElementsByTagName("p");
else var el = document.registerform.getElementsByTagName("p");
for(var i=0;i<el.length;i++){ 
el[i].style["display"] = "none"; 
} 
document.getElementById("normal-login-text").style["display"] = "block";
document.getElementById("connect-login-text").style["display"] = "none";
document.getElementById("connect-with").style["display"] = "block";
document.getElementById("social-icons").style["display"] = "block";
}
</script>';
}

}

add_filter('login_headerurl', 'tt_tebe_change_wp_login_url');
// CUSTOM ADMIN LOGIN LOGO LINK
function tt_tebe_change_wp_login_url()
{
	return get_bloginfo('url');
}

add_filter('login_headertitle', 'tt_tebe_change_wp_login_title');
// CUSTOM ADMIN LOGIN LOGO & ALT TEXT
function tt_tebe_change_wp_login_title()
{
	return get_option('blogname');
}

add_filter('authenticate','tt_tebe_login_check');
function tt_tebe_login_check($user) {
	global $wpdb;
	global $tt_tebe_user_profile;
	global $tt_tebe_refresh_token;
	global $tt_tebe_access_token;
	if ( is_a($user, 'WP_User') ) { return $user; } // check if user is already logged in, skip FB stuff
	
	if (!empty($tt_tebe_user_profile['email'])) {
		
				$user_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_email = %s", $tt_tebe_user_profile['email']) );
	//check the next condition.......................................			
					if ($user_id) {
//						do_action('wp_login', $user->user_login, $user);
						$user = new WP_User($user_id);
//						wp_set_auth_cookie($user->ID, true);
//						do_action('wp_login', $user->user_login, $user);
//						$user = wp_get_current_user();
						update_user_meta($user_id, 'connect_provider', $tt_tebe_user_profile['provider']);
//						if($tt_tebe_user_profile['provider'] == 'facebook') update_user_meta($user_id, 'access_token', $tt_tebe_access_token);
//						elseif($tt_tebe_user_profile['provider'] == 'google') update_user_meta($user_id, 'refresh_token', $tt_tebe_refresh_token);
					}
					else { //create new user account
/*						$tt_tebe_post = array(
							'user_login'=>$tt_tebe_user_profile['id'],
							'user_email'=>$tt_tebe_user_profile['email']
							);
     				   foreach($tt_tebe_post as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
							rtrim($fields_string,'&');
			
						$ch = curl_init();

						//set the url, number of POST vars, POST data
						curl_setopt($ch,CURLOPT_URL,site_url('/wp-login.php?action=register'));
						curl_setopt($ch,CURLOPT_POST,count($tt_tebe_post));
						curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

						//execute post
						$result = curl_exec($ch);

						//close connection
						curl_close($ch);
*/						

if(isset($tt_tebe_user_profile['first_name'])) $tt_tebe_first_name = $tt_tebe_user_profile['first_name'];
else if (isset($tt_tebe_user_profile['given_name'])) $tt_tebe_first_name = $tt_tebe_user_profile['given_name'];
else $tt_tebe_first_name = '';

if(isset($tt_tebe_user_profile['last_name'])) $tt_tebe_last_name = $tt_tebe_user_profile['last_name'];
else if (isset($tt_tebe_user_profile['family_name'])) $tt_tebe_last_name = $tt_tebe_user_profile['family_name'];
else $tt_tebe_last_name = '';

$user_id = wp_insert_user( array ('user_login' => $tt_tebe_user_profile['email'], 'user_email' => $tt_tebe_user_profile['email'], 'user_nicename' => $tt_tebe_user_profile['name'], 'nickname' => $tt_tebe_user_profile['name'], 'display_name' => $tt_tebe_user_profile['name'], 'first_name' => $tt_tebe_first_name, 'last_name' => $tt_tebe_last_name ) ) ;

update_user_meta($user_id, 'connect_provider', $tt_tebe_user_profile['provider']);
$user = new WP_User($user_id);
//wp_set_auth_cookie($user->ID, true);
//do_action('wp_login', $user->user_login, $user);





class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      
 
}




//*******************************************************************************
//*******************************************************************************
//*******************************************************************************

//update_user_meta($user_id, 'avatar_thumb', $tt_tebe_access_token);


						
						if ( $tt_tebe_refresh_token && $user_id) {
								update_user_meta($user_id, 'refresh_token', $tt_tebe_refresh_token);
								$tt_tebe_refresh_token = NULL;
						}
						elseif ( $tt_tebe_access_token && $user_id) {
								update_user_meta($user_id, 'access_token', $tt_tebe_access_token);
								$tt_tebe_access_token = NULL;
						}
											
						add_filter('login_message', 'tt_tebe_register_successful_message');
						function tt_tebe_register_successful_message() {
							$message = "<p class='message'>Account Successfully Created. Please Connect using Facebook.</p>";// chage face book to google yyahoo etc
							return $message;
						}
					}
			}
			else {
				add_filter('login_message', 'tt_tebe_login_logout_message');
				function tt_tebe_login_logout_message($message) {
								$message = "<p class='message'>Please Login to gain access to all downloads.</br>Click here to <a href='wp-login.php?action=register' >Register</a> for 25 labs.</p>";
							return $message;
				}
		}
	return $user;
}


add_action('wp_logout', 'tt_tebe_login_redirect');
function tt_tebe_login_redirect() {
	
	$tt_tebe_options = get_option('tt_tebe_options');	
//	setcookie('tt_tebe_' . $tt_tebe_options['facebook-app-id'], 0, time()-60*60*24*365, "/");
	list($temp,$temp2) = explode('.', $tt_tebe_options['google-client-id'], 2);
//	setcookie('tt_tebe_' . $temp, 0, time()-60*60*24*365, "/");
	
	//remove next 2 lines to display message "you are not logged out"
//	wp_redirect( site_url('/wp-login.php') );
//	exit;	
}

function tt_tebe_my_login_redirect($redirect_to){
	if(isset($_COOKIE['redirect_to'])) {
		$redirect_to = $_COOKIE['redirect_to'];
		setcookie ( 'redirect_to', $_REQUEST['redirect_to'], time()-3600);
	}else{
		$redirect_to = site_url();
	}
	return $redirect_to;
}
add_filter("login_redirect", "tt_tebe_my_login_redirect");

// Remove Wordpress 3.3 Dashboard Crap
function tt_tebe_dashboard_tweaks() {
	global $wp_admin_bar;
	$wp_admin_bar->remove_menu('wp-logo');
	$wp_admin_bar->remove_menu('about');
	$wp_admin_bar->remove_menu('wporg');
	$wp_admin_bar->remove_menu('documentation');
	$wp_admin_bar->remove_menu('support-forums');
	$wp_admin_bar->remove_menu('feedback');
	$wp_admin_bar->remove_menu('view-site');
}
add_action( 'wp_before_admin_bar_render', 'tt_tebe_dashboard_tweaks' );


add_filter( 'auth_cookie_expiration', 'tt_tebe_keep_me_logged_in_for_1_year' );
function tt_tebe_keep_me_logged_in_for_1_year( $expire ) {
    return 31556926; // 1 year in seconds
}

//add_filter( 'auth_cookie_expiration', 'tt_tebe_force_remember' );
function tt_tebe_force_remember( $remember ) {
    return TRUE; // force remember
}


//add_filter('get_avatar', 'tt_tebe_avatar', 10, 5);
function tt_tebe_avatar($avatar, $id_or_email, $size, $default, $alt) {
    //First, get the userid
    if (is_numeric($id_or_email))       
        $user_id = $id_or_email;
    else if(is_object($id_or_email) && !empty($id_or_email->user_id))
       $user_id = $id_or_email->user_id;
    else if(is_string($id_or_email))
       $user_id = get_user_by('email', $id_or_email ); 

    //If we couldn't get the userID, just return default behavior (email-based gravatar, etc)
    if(!isset($user_id) || !$user_id) return $avatar;

    //Now that we have a userID, let's see if we have their facebook profile pic stored in usermeta
 //   $fb_img = get_usermeta($user_id, 'facebook_avatar_thumb');

    //If so, replace the avatar! Otherwise, fallback on what WP core already gave us.
 //   if($fb_img) 
 
 
 
//    $avatar = "<img alt='fb_avatar' src='https://graph.facebook.com/tebetensing/picture?type=small' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
//    $avatar = "<img alt='fb_avatar' src='https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/49942_4_1525300_n.jpg' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
    
    
//    $avatar = '<img class="avatar avatar-64 photo" width="64" height="64" src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/49942_4_1525300_n.jpg" alt="">';
    
    
    
    
    return $avatar;
}

if (!function_exists('disableAdminBar')) {

	function disableAdminBar(){

//  	remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 ); // for the admin page
    remove_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); // for the front end

    function remove_admin_bar_style_backend() {  // css override for the admin page
      echo '<style>body.admin-bar #wpcontent, body.admin-bar #adminmenu { padding-top: 0px !important; }</style>';
    }

//    add_filter('admin_head','remove_admin_bar_style_backend');

    function remove_admin_bar_style_frontend() { // css override for the frontend
      echo '<style type="text/css" media="screen">
      html { margin-top: 0px !important; }
      * html body { margin-top: 0px !important; }
      </style>';
    }

    add_filter('wp_head','remove_admin_bar_style_frontend', 99);

  }

}
// add_filter('admin_head','remove_admin_bar_style_backend'); // Original version
add_action('init','disableAdminBar'); // New version remove admin bar

add_filter( 'the_content', 'my_the_content_filter', 20 );
function my_the_content_filter( $content ) {
	$output = preg_match_all('/<a.+href=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
	$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
	if ($_SERVER["SERVER_PORT"] != "80")
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	else
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

	if ( !is_user_logged_in() ) {
  		foreach($matches[1] as $link){  	
  			if((strlen($link) - strripos($link,'.zip') == 4)){
  				$content = str_ireplace($link,wp_login_url($pageURL),$content);
  			} 

  		}
  	}
    return $content;
}

?>